package pactera.tf.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import pactera.tf.dataobj.GroupChatDO;
import pactera.tf.dataobj.GroupInfoDO;
import pactera.tf.dto.ChatGroupDTO;
import pactera.tf.excpetion.CmsException;
import pactera.tf.mapper.GroupInfoMapper;
import pactera.tf.service.GroupChatService;
import pactera.tf.service.GroupInfoService;

@Service
public class GroupInfoServiceImpl implements GroupInfoService{
    @Autowired
    GroupInfoMapper groupInfoMapper;

    @Autowired
    private GroupChatService chatGroupService;

    @Override
    public List<GroupInfoDO> listAllGroup(String userid){
        return groupInfoMapper.listAllGroup(userid);
    }

    @Override
    public void addGroupInfo(GroupInfoDO groupInfo){
    	groupInfoMapper.addGrop(groupInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createGroupInfo(ChatGroupDTO chatGroupDTO) {
        GroupInfoDO groupInfo = new GroupInfoDO();
        groupInfo.setGroupCreaterId(chatGroupDTO.getGroupcreaterid());
        groupInfo.setGroupName(chatGroupDTO.getGroupname());
        GroupInfoDO groupByName = groupInfoMapper.getSearchGroupByName(groupInfo.getGroupName());
        //已经创建了该组 则不可以再次创建
        if(groupByName != null ){
            throw new CmsException(2000,"群信息已经存在");
        }
        int result = groupInfoMapper.createGroupInfo(groupInfo);
        //组信息创建成功 同时将创建者放到聊天组中
        if (result ==1){
            GroupChatDO chatGroupInfo = new GroupChatDO();
            chatGroupInfo.setGroupId(groupInfo.getGroupId());
            chatGroupInfo.setGroupUserNickName(chatGroupDTO.getGroupusernickname());
            chatGroupInfo.setUserId(chatGroupDTO.getUserid());
            chatGroupService.addUserToChatGroup(chatGroupInfo);

        }
        return result;
    }

    @Override
    public GroupInfoDO getSearchGroupByName(String groupName) {
        return groupInfoMapper.getSearchGroupByName(groupName);
    }
}
